<?php
/**
 * 订单逻辑
 * 作者：MYL
 */
namespace app\api\controller;

use app\api\model\OrderModel;
use app\api\model\UserModel;
use app\common\logic\CartLogic;
use app\common\util\TpshopException;
use think\Db;
use think\Loader;
use app\common\logic\Pay;
use app\common\logic\PlaceOrder;

class Order extends Base
{
    /**
     * 确认订单(立即购买)
     */
    public function confirm()
    {
        $user_id = I("post.user_id"); // 用户id
        $goods_id = I("post.goods_id/d"); // 商品id
        $item_id = I("post.item_id/d"); // 商品规格id
        $goods_num = I("post.goods_num/d");// 商品数量

        $cartLogic = new CartLogic();
        $cartLogic->setUserId($user_id);
        //立即购买
        $cartLogic->setGoodsModel($goods_id);
        $cartLogic->setSpecGoodsPriceById($item_id);
        $cartLogic->setGoodsBuyNum($goods_num);
        $buyGoods = [];
        try{
            $buyGoods = $cartLogic->buyNow();
        }catch (TpshopException $t){
            $error = $t->getErrorArr();
            $this->error($error['msg']);
        }
        $cartList['cartList'][0] = $buyGoods;
        $cartGoodsTotalNum = $goods_num;

        $cartPriceInfo = $cartLogic->getCartPriceInfo($cartList['cartList']);  //初始化数据。商品总额/节约金额/商品总共数量
        $cartList = array_merge($cartList,$cartPriceInfo);
        ajaxReturn(['status' => 1, 'msg' => '获取订单列表成功！', 'result' => $cartList['cartList'], 'cartGoodsTotalNum' => $cartGoodsTotalNum]);
    }

    /**
     * 提交订单
     */
    public function placeOrder()
    {
        $order_data = array();
        $user_id = I('post.user_id'); //用户id
        $goods_id = I("post.goods_id/d"); // 商品id
        $goods_num = I("post.goods_num/d");// 商品数量
        $item_id = I("post.item_id/d"); // 商品规格id
        $pay_code = I("post.pay_code");//支付方式（code:余额支付，aliPay:支付宝，wxPay:微信）
        $coupon_id = I("post.coupon_id/d"); //  优惠券id
        $user_note = I("post.user_note/s", ''); // 用户留言
        //选择了余额支付（需要传$payPwd）
        $payPwd = I("post.payPwd/s", ''); // 支付密码

        $data = I('request.');
        $cart_validate = Loader::validate('Cart');
        //检查参数格式
        if (!$cart_validate->check($data)) {
            $error = $cart_validate->getError();
            ajaxReturn(['status' => 0, 'msg' => $error[0], 'result' => array()]);
        }
        // 判断该用户是否购买过该产品，如果买过，查看是否到期, 是否支付！！！
        $renew = new OrderModel();
        $row = $renew::orderRenew($goods_id,$user_id);
        if ($row == 0) {
            ajaxReturn(['status' => -1, 'msg' => '该商品您已经购买过，未支付，请去订单管理支付！']);
        }
        if ($row == 2){
            ajaxReturn(['status' => -1, 'msg' => '您已经购买过次商品，未到期，无需购买！']);
        }
        //验证余额支付密码是否正确
        if ($pay_code=='code'){
            $is_pwd = OrderModel::judgePassword($user_id,$payPwd);
            if ($is_pwd == 2) {
                ajaxReturn(['status' => -1, 'msg' => '支付密码不正确，请重新输入！']);
            }
        }
        //设置需要的参数（订单表，订单记录表，订单商品表）
        $cartLogic = new CartLogic();
        $pay = new Pay();
        try {
            //判断用户支付方式
            if ($pay_code=='aliPay') {
                $type['pay_name'] = '支付宝支付';
            } else if ($pay_code=='wxPay'){
                $type['pay_name'] = '微信支付';
            } else if ($pay_code=='code'){
                $type['pay_name'] = '余额支付';
            } else {
                $type['pay_name'] = '其他方式支付';
            }
            //设置用户ID
            $cartLogic->setUserId($user_id);
            $pay->setUserId($user_id);
            //立即购买
            $cartLogic->setGoodsModel($goods_id);
            $cartLogic->setSpecGoodsPriceById($item_id);
            $cartLogic->setGoodsBuyNum($goods_num);
            $buyGoods = $cartLogic->buyNow(); //立即购买
            $cartList[0] = $buyGoods;
            $pay->payGoodsList($cartList); //计算购买商品表的商品
            //金钱的变动
            $pay->useCouponById($coupon_id); //使用优惠券（用户个人的优惠券）
            // 提交订单
            $placeOrder = new PlaceOrder($pay);
            $placeOrder->setUserNote($user_note); //设置留言
            $placeOrder->setPayCode($pay_code); //设置支付方式
            $placeOrder->setPayPsw($payPwd); //设置密码
            $placeOrder->addNormalOrder(); //添加正常de订单
            $order = $placeOrder->getOrder(); //获取订单表数据
            $order_data['order_sn'] = $order['order_sn'];
            $order_data['order_calculate'] = $pay->toArray();
            $order_data['pay_type'] = $order['pay_code'];
            //修改支付状态
            M('order')->where('order_sn',$order_data['order_sn'])->update($type);
            //判断是否是 新购 ，如果是续费
            if ($row == 1) {
                M('order')->where('order_sn',$order_data['order_sn'])->update(['order_type'=>2]);
            } if($row == 3) {
                M('order')->where('order_sn',$order_data['order_sn'])->update(['order_type'=>1]);
            }
//            /**修改用户账户余额（余额支付才走此地）*/
//            if ($pay_code=='code'){
//                OrderModel::updateBalance($order_data['order_sn'],$order_data['order_calculate']['order_amount']);
//            }
            ajaxReturn(['status' => 1, 'msg' => '提交订单成功', 'result' => $order_data]);
        } catch (TpshopException $t) {
            $error = $t->getErrorArr();
            ajaxReturn($error);
        }
    }

    /**
     * 订单列表/我的订单
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function orderList()
    {
        $user_id = I("post.user_id");
        $page = I('post.page', 1);
        $order_type = I('post.order_type', 0);
        $order_status = I('post.order_status', 0);
        $add_time = I('post.add_time', 0);

        $bind['user_id'] = $user_id;
        //判断类型（新购，续费）
        if ($order_type>0) {
            $bind['order_type'] = $order_type;
        }
        //判断支付状态（未支付，已支付，作废）
        if ($order_status == 1) {
            $bind['pay_status'] = 1;
        } if ($order_status == 2) {
            $bind['pay_status'] = 0;
        } if ($order_status==3) {
            $bind['order_status'] = 5;
        }
        //判断时间（前3个月，前3-6个月，一年前）
        $mtime3 = strtotime(date("Y-m-d H:i:s", strtotime("-3 month")));
        $mtime6 = strtotime(date("Y-m-d H:i:s", strtotime("-6 month")));
        $mtimeNew = strtotime(date("Y-m-d H:i:s", strtotime("-1 year")));
        if ($add_time == 1) {
            $bind['add_time'] = array('gt',$mtime3);
        } if ($add_time == 2) {
            $bind['add_time'] = array('gt',$mtime6);
            //$bind['add_time'] = array('between', array($mtime3,$mtime6));
        } if ($add_time==3) {
            $bind['add_time'] = array('gt',$mtimeNew);
        }

        $order_str = "order_id DESC";
        $order_list = Db::name('order')->field("order_id,order_sn,user_id,order_status,FROM_UNIXTIME(add_time,'%Y-%m-%d %H:%i:%s') as add_time,pay_name,total_amount,order_amount,order_prom_amount,pay_status,deleted,invoice_title,taxpayer,order_type")->order($order_str)->where($bind)->page($page, 20)->select();//->where($where2)->bind($bind)

        //获取订单商品
        foreach ($order_list as $k => $v) {
            //$order_list[$k] = set_btn_order_status($v); //获取订单 状态 和 状态码

            $sql = "SELECT og.order_id,og.goods_id,og.goods_name,og.goods_num,g.original_img FROM __PREFIX__order_goods og LEFT JOIN __PREFIX__goods g ON g.goods_id = og.goods_id WHERE order_id =" . $v['order_id'];
            $order_goods_data = DB::query($sql);
            $order_list[$k]['goods_list'] = $order_goods_data; //获取订单商品信息（订单ID,商品ID,商品数量，商品图片）

            //统计订单商品总数
            $total_goods = M("order_goods")->where('order_id', $v['order_id'])->sum('goods_num');
            $order_list[$k]['total_goods'] = $total_goods;

            //判断订单类型
            if ($v['order_type']==1){
                $order_list[$k]['order_type'] = '新购';
            } else if ($v['order_type']==2) {
                $order_list[$k]['order_type'] = '续费';
            } else {
                $order_list[$k]['order_type'] = '新购2';
            }
        }
        if (!empty($order_list)) {
            ajaxReturn(['status' => 1, 'msg' => '获取订单列表成功！', 'result' => $order_list]);
        } else {
            ajaxReturn(['status' => 0, 'msg' => '获取订单列表失败！', 'result' => array()]);
        }
    }

    /**
     * 订单支付（判断）
     * 先查询余额是否大于订单，大于就用余额支付，小于就是用微信支付！！！
     */
    public function twoPay()
    {
        $user_id = I("post.user_id");
        $order_id = I("post.order_id");

        $where['order_id'] = $order_id;
        $where['user_id'] = $user_id;
        $order = Db::name('order')->field('order_sn,order_amount')->where($where)->find();
        $users = Db::name('users')->field('user_money')->where('user_id',$user_id)->find();
        $order_amount = floor($order['order_amount']); //舍去法取整
        $order['order_amount'] = $order_amount;
        if($order['order_amount'] > $users['user_money']) {
            //余额不足，微信支付
            ajaxReturn(['status' => 1, 'order' => $order]);
        } else {
            //余额充足，余额支付
            ajaxReturn(['status' => -1, 'order' =>$order]);
        }
    }

    /**
     * 订单作废
     */
    public function orderWaste()
    {
        $user_id = I("post.user_id");
        $order_id = I("post.order_id");

        $where['order_id'] = $order_id;
        $where['user_id'] = $user_id;
        $rs = M('order')->where($where)->update(['order_status' => 5]);
        if (!empty($rs)) {
            ajaxReturn(['status' => 1, 'msg' => '订单已作废！']);
        } else {
            ajaxReturn(['status' => 0, 'msg' => 'Error！']);
        }
    }

    /**
     * 订单详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function order_detail()
    {
        ajaxReturn(['status' => -1, 'msg' => '该接口已暂停，请联系管理员！']);
        $user_id = I("post.user_id");
        $order_id = I('post.order_id');

        $order = M('order')->where(['order_id' => $order_id, 'user_id' => $user_id])->select();//订单信息

        foreach ($order as $k => $v) {
            //详细收货地址
            if ($v['country'] == 0) $v['country'] = '中国';
            $province = M('region')->field('name')->where('id', $v['province'])->find();
            $v['province'] = $province['name'];//省份
            $city = M('region')->field('name')->where('id', $v['city'])->find();
            $v['city'] = $city['name'];//城市
            $district = M('region')->field('name')->where('id', $v['district'])->find();
            $v['district'] = $district['name'];//县区
            $twon = M('region')->field('name')->where('id', $v['twon'])->find();
            $v['twon'] = $twon['name'];//乡镇

            //获取订单状态
            $order[$k] = set_btn_order_status($v);

            //获取订单商品信息
            $data = $this->get_order_goods($v['order_id']);
            $order[$k]['goods_list'] = $data;

            if ($v['order_status'] == 3 && ($v['pay_status'] == 1 || $v['pay_status'] == 4 || $v['pay_status'] == 3)) {
                $order[$k]['cancel_info'] = 1; //取消订单详情
            }
        }
        if (!empty($order)) {
            ajaxReturn(['status' => 1, 'msg' => '获取订单详情成功！', 'result' => $order]);
        } else {
            ajaxReturn(['status' => -1, 'msg' => '获取失败订单不存在！', 'result' => array()]);
        }
    }
    /**
     * 获取订单商品信息
     * @param $order_id
     * @return mixed
     */
    public function get_order_goods($order_id)
    {
        $sql = "SELECT og.*,g.goods_id,g.goods_sn,g.goods_name,g.original_img FROM __PREFIX__order_goods og LEFT JOIN __PREFIX__goods g ON g.goods_id = og.goods_id WHERE order_id = :order_id";
        $bind['order_id'] = $order_id;
        $goods_list = DB::query($sql, $bind);
        return $goods_list;
    }

}